package cn.store.web.servlet;

import cn.store.service.serviceImp.CategoryServiceImp;
import cn.store.domain.Category;
import cn.store.domain.PageModel;
import cn.store.domain.Product;
import cn.store.service.CategoryService;
import cn.store.service.ProductService;
import cn.store.service.serviceImp.ProductServiceImp;
import cn.store.utils.UUIDUtils;
import cn.store.utils.UploadUtils;
import cn.store.web.base.BaseServlet;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdminProductServlet extends BaseServlet {
	//分页+搜索
	public String findAllProductsWithPage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//获取当前页
		String num = req.getParameter("num");
		int curNum;
		if(num != null){
			curNum=Integer.parseInt(req.getParameter("num"));
		}else {
			curNum = 1;
		}
		//获取pname搜索词
		Integer is_hot;
		if( req.getParameter("is_hot") == null || "-1".equals(req.getParameter("is_hot"))){
			is_hot = null;
		}else{
			is_hot = Integer.parseInt( req.getParameter("is_hot"));
		}
		Integer pflag;       //商品的上架下架
		if( req.getParameter("pflag") == null || "-1".equals(req.getParameter("pflag"))){
			pflag = null;
		}else{
			pflag = Integer.parseInt( req.getParameter("pflag"));
		}
		String pname = req.getParameter("pname");
		String cid = req.getParameter("cid");
		//封装搜索词
		Map<String,Object> searchWords = new HashMap<>();
		searchWords.put("is_hot",is_hot);
		searchWords.put("pflag",pflag);
		searchWords.put("pname",pname);
		searchWords.put("cid",cid);

		//调用业务层查全部商品信息返回PageModel
		ProductService ProductService=new ProductServiceImp();
		PageModel pm=ProductService.findAllProductsWithPage(curNum,searchWords);
		//将PageModel放入request
		req.setAttribute("page", pm);


		//包装回搜索词,防止页面跳转丢失
		Product searchProduct = new Product();
		searchProduct.setCid(cid);
		if(is_hot != null){
			searchProduct.setIs_hot(is_hot);
		}else {
			searchProduct.setIs_hot(-1);
		}
		if(pflag != null){
			searchProduct.setPflag(pflag);
		}else {
			searchProduct.setPflag(-1);
		}
		searchProduct.setPname(pname);
		req.setAttribute("searchProduct", searchProduct);
		//加载分类类目
		CategoryService CategoryService=new CategoryServiceImp();
		//获取全部分类信息
		List<Category> list = CategoryService.getAllCats();
		//将全部分类信息放入request
		req.setAttribute("allCats", list);

		//转发到/admin/product/list.jsp
		return "/admin/product/list.jsp";
	}
	
	//addProductUI
	public String addProductUI(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		CategoryService CategoryService=new CategoryServiceImp();
		//获取全部分类信息
		List<Category> list = CategoryService.getAllCats();
		//将全部分类信息放入request
		req.setAttribute("allCats", list);
		//转发到/admin/product/add.jsp
		return "/admin/product/add.jsp";
	}
	//addProduct
	public String addProduct(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//存储表单中数据
		Map<String,String> map=new HashMap<String,String>();
		//携带表单中的数据向servcie,dao
		Product product=new Product();
		try {
			//利用req.getInputStream();获取到请求体中全部数据,进行拆分和封装
			DiskFileItemFactory fac=new DiskFileItemFactory();    //创建工厂类
			ServletFileUpload upload=new ServletFileUpload(fac);  //创建解析器：
			List<FileItem> list=upload.parseRequest(req);         //使用解析器解析request对象：
			//4_遍历集合
			for (FileItem item : list) {
				if(item.isFormField()){
					//5_如果当前的FileItem对象是普通项
					//将普通项上name属性的值作为键,将获取到的内容作为值,放入MAP中
					// {username<==>tom,password<==>1234}
					map.put(item.getFieldName(), item.getString("utf-8"));
				}else{
					//6_如果当前的FileItem对象是上传项
					
					//获取到原始的文件名称
					String oldFileName=item.getName();
					//获取到要保存文件的名称   1222.doc  123421342143214.doc
					String newFileName=UploadUtils.getUUIDName(oldFileName);
					
					//通过FileItem获取到输入流对象,通过输入流可以获取到图片二进制数据
					InputStream is=item.getInputStream();
					//获取到当前项目下products/3下的真实路径
					//D:\tomcat\tomcat71_sz07\webapps\store_v5\products\3
					String realPath=getServletContext().getRealPath("/products/3/");
					String dir=UploadUtils.getDir(newFileName); // /f/e/d/c/4/9/8/4
					String path=realPath+dir; //D:\tomcat\tomcat71_sz07\webapps\store_v5\products\3/f/e/d/c/4/9/8/4
					//内存中声明一个目录
					File newDir=new File(path);
					if(!newDir.exists()){
						newDir.mkdirs();
					}
					//在服务端创建一个空文件(后缀必须和上传到服务端的文件名后缀一致)
					File finalFile=new File(newDir,newFileName);
					if(!finalFile.exists()){
						finalFile.createNewFile();
					}
					//建立和空文件对应的输出流
					OutputStream os=new FileOutputStream(finalFile);
					//将输入流中的数据刷到输出流中
					IOUtils.copy(is, os);
					//释放资源
					IOUtils.closeQuietly(is);
					IOUtils.closeQuietly(os);
					//向map中存入一个键值对的数据 userhead<===> /image/11.bmp
					// {username<==>tom,password<==>1234,userhead<===>image/11.bmp}
					map.put("pimage", "/products/3/"+dir+"/"+newFileName);
				}
			}

			
			//7_利用BeanUtils将MAP中的数据填充到Product对象上
			BeanUtils.populate(product, map);
			product.setPid(UUIDUtils.getId());
			product.setPdate(new Date());
			
			//8_调用servcie_dao将user上携带的数据存入数据仓库,重定向到查询全部商品信息路径
			ProductService ProductService=new ProductServiceImp();
			ProductService.saveProduct(product);
			/*跳转页面*/
			resp.sendRedirect(req.getContextPath()+"/AdminProductServlet?method=findAllProductsWithPage&num=1");
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	/*
	 * 通过pid查询商品
	 * */
	public String findProductByPid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String pid = req.getParameter("pid");
		ProductService productService=new ProductServiceImp();
		Product product = productService.findProductByPid(pid);
		req.setAttribute("product",product);

		CategoryService CategoryService=new CategoryServiceImp();
		//获取全部分类信息
		List<Category> list = CategoryService.getAllCats();
		//将全部分类信息放入request
		req.setAttribute("allCats", list);

		return "/admin/product/edit.jsp";
	}

	//修改Product
	public String updateProduct(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//存储表单中数据
		Map<String,String> map=new HashMap<String,String>();
		//携带表单中的数据向servcie,dao
		Product product=new Product();
		try {
			//利用req.getInputStream();获取到请求体中全部数据,进行拆分和封装
			DiskFileItemFactory fac=new DiskFileItemFactory();
			ServletFileUpload upload=new ServletFileUpload(fac);
			List<FileItem> list=upload.parseRequest(req);
			//4_遍历集合
			for (FileItem item : list) {
				if(item.isFormField()){
					//5_如果当前的FileItem对象是普通项
					//将普通项上name属性的值作为键,将获取到的内容作为值,放入MAP中
					// {username<==>tom,password<==>1234}
					map.put(item.getFieldName(), item.getString("utf-8"));
				}else{
					String oldFileName=item.getName();
					/*前台没有上传就不修改*/
					if(oldFileName!=null&&!"".equals(oldFileName)) {
						//6_如果当前的FileItem对象是上传项
						//获取到原始的文件名称

						//获取到要保存文件的名称   1222.doc  123421342143214.doc
						String newFileName = UploadUtils.getUUIDName(oldFileName);
						//通过FileItem获取到输入流对象,通过输入流可以获取到图片二进制数据
						InputStream is = item.getInputStream();
						//获取到当前项目下products/3下的真实路径
						//D:\tomcat\tomcat71_sz07\webapps\store_v5\products\3
						String realPath = getServletContext().getRealPath("/products/3/");
						String dir = UploadUtils.getDir(newFileName); // /f/e/d/c/4/9/8/4
						String path = realPath + dir; //D:\tomcat\tomcat71_sz07\webapps\store_v5\products\3/f/e/d/c/4/9/8/4
						//内存中声明一个目录
						File newDir = new File(path);
						if (!newDir.exists()) {
							newDir.mkdirs();
						}
						//在服务端创建一个空文件(后缀必须和上传到服务端的文件名后缀一致)
						File finalFile = new File(newDir, newFileName);
						if (!finalFile.exists()) {
							finalFile.createNewFile();
						}
						//建立和空文件对应的输出流
						OutputStream os = new FileOutputStream(finalFile);
						//将输入流中的数据刷到输出流中
						IOUtils.copy(is, os);
						//释放资源
						IOUtils.closeQuietly(is);
						IOUtils.closeQuietly(os);
						//向map中存入一个键值对的数据 userhead<===> /image/11.bmp
						// {username<==>tom,password<==>1234,userhead<===>image/11.bmp}
						map.put("pimage", "/products/3/" + dir + "/" + newFileName);
					}
				}
			}
			//7_利用BeanUtils将MAP中的数据填充到Product对象上
			BeanUtils.populate(product, map);
			product.setPdate(new Date());
			//8_调用servcie_dao将user上携带的数据存入数据仓库,重定向到查询全部商品信息路径
			ProductService ProductService=new ProductServiceImp();
			ProductService.updateProduct(product);
			resp.sendRedirect(req.getContextPath()+"/AdminProductServlet?method=findAllProductsWithPage&num=1");

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/*
	 * 通过pid刪除商品
	 * */
	public String deleteProduct(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String pid = req.getParameter("pid");
		Map<String,String> msg = new HashMap<>();
		resp.setContentType("application/json; charset=utf-8");
		PrintWriter p =resp.getWriter();
		try {
			/*尝试删除*/
			ProductService ProductService=new ProductServiceImp();
			if(ProductService.deleteProduct(pid) > 0){
				msg.put("flag","true");
			}else{
				msg.put("flag","false");
			}

		}catch (Exception e){
			/*删除失败*/
			msg.put("flag","false");
		}finally {
			String jsonStr = JSON.toJSONString(msg);
			System.out.println(jsonStr);
			p.write(jsonStr);
			return null;
		}

	}
}
